<?php

/***
 * Class UserModel
 * 用户表
 */
class UserModel extends PdoModel
{
    protected $_name = 'user';

    const USER_LOGIN_INFO_KRY = 'user_login_info_';  //用户登陆信息缓存
    const USER_LOGIN_INFO_CACHETIME = 60*60;  //用户信息缓存时间

    const USER_LOCATION = 'user_location_';  //用户定位过信息缓存


    function __construct(){
        parent::__construct();
    }

    #添加
    function addData($data){
        if(empty($data)){
            return false;
        }

        try {
            return $this->insert($data);
        }catch(Exception $ex){
            $this->logException($ex->getMessage());
            return false;
        }
    }

    #删除
    function deleteDate($uid){
        if(empty($uid)){
            return false;
        }

        $ret = $this->delete(' uid = '. $uid);
        return $ret;
    }

    #更新
    function updateData($data,$uid){
        return $this->update($data,"uid = {$uid}");
    }


       function checkisLogin() {
        if(isset($_REQUEST['access_token'])){
            $access_token = $_REQUEST['access_token'];
            #如果有缓存，就用idfa获取uid,去实时查询，没有获取到对应的消息就用idfa去查询
            $redis = new Config_RedisModel();
            $redis_key = SELF::USER_LOGIN_INFO_KRY . $access_token;
            $userinfo_cash = $redis->getData($redis_key);

            #实时查询用户信息
            if(!empty($userinfo_cash['uid'])){
                $userinfo = $this->getUserInfoByUid($userinfo_cash['uid']);
            }else{
                $userinfo = $this->getUserInfoByToken($access_token);
            }

            if (!empty($userinfo['uid'])) {
                $redis->setData($redis_key, $userinfo, self::USER_LOGIN_INFO_CACHETIME);  //缓存新的用户信息
                return $userinfo;
            }

            #清除用户信息
            $redis_key = UserModel::USER_LOGIN_INFO_KRY . $access_token;
            $redis->setData($redis_key, 1, 1);
        }

        if (isset($_COOKIE['swidfa']) && !empty($_COOKIE['swidfa'])) {
            $idfa = $_COOKIE['swidfa'];

            #如果有缓存，就用idfa获取uid,去实时查询，没有获取到对应的消息就用idfa去查询
            $redis = new Config_RedisModel();
            $redis_key = SELF::USER_LOGIN_INFO_KRY . $idfa;
            $userinfo_cash = $redis->getData($redis_key);

            #实时查询用户信息
            if(!empty($userinfo_cash['uid'])){
                $userinfo = $this->getUserInfoByUid($userinfo_cash['uid']);
            }else{
                $userinfo = $this->getUserInfoByDeviceserial($idfa);
            }

            if (!empty($userinfo['uid'])) {
                $redis->setData($redis_key, $userinfo, self::USER_LOGIN_INFO_CACHETIME);  //缓存新的用户信息
                return $userinfo;
            }

            #清除用户信息和idfa的缓存
            setcookie('swidfa', $idfa, time()-1, '/');
            $redis_key = UserModel::USER_LOGIN_INFO_KRY . $idfa;
            $redis->setData($redis_key, 1, 1);
        }

        if(isset($_COOKIE['swuser']) && !empty($_COOKIE['swuser'])){
            $user = (array)json_decode($_COOKIE['swuser']);
            if(!empty($user['uid'])) {
                $userinfo = $this->getUserInfoByUid($user['uid']);
                if(!empty($userinfo['uid'])) {
                    $redis = new Config_RedisModel();
                    $redis_key = SELF::USER_LOGIN_INFO_KRY . $userinfo['device_serial'];
                    $redis->setData($redis_key, $userinfo, self::USER_LOGIN_INFO_CACHETIME);  //缓存新的用户信息
                    return $userinfo;
                }

                #清除缓存
                setcookie('swuser', json_decode($user), time()-1, '/');
            }
        }
        return false;
    }


    #获取缓存的idfa对应的用户信息，针对不需要实时的用户信息
    function getUserInfoCacheByDeviceserial($device_serial){
        if(empty($device_serial)) {
            return False;
        }

        #获取缓存用户信息
        $redis = new Config_RedisModel();
        $redis_key = SELF::USER_LOGIN_INFO_KRY . $device_serial;
        $data = $redis->getData($redis_key);

        #缓存用户信息为空的时候去实时查询
        if(empty($data)){
            $sql = "select uid, mobile, access_token,frozen, ios_model, ios_version, now_idfa, device_serial,udid ,address,ban_memo,birthday,unionid,excel,add_up,balance from {$this->_name} where device_serial='{$device_serial}' limit 1 ";
            $data = $this->fetchRow($sql);
            $redis->setData($redis_key, $data, self::USER_LOGIN_INFO_CACHETIME);  //缓存用户信息
        }

        return $data;
    }

    #获取缓存的idfa对应的用户信息，针对不需要实时的用户信息
    function getUserInfoByAccessToken($access_token){
        if(empty($access_token)) {
            return False;
        }

        #缓存用户信息为空的时候去实时查询
        $sql = "select uid from {$this->_name} where access_token='{$access_token}' limit 1 ";
        $uid = $this->fetchRow($sql);

        return $uid;
    }


    function getUserInfoByUid($uid = 0){
        if($uid <= 0){
            return false;
        }

        $sql = "select * from user where uid = {$uid}";
        $data = $this->fetchRow($sql);
        return $data;
    }

    function getUserInfoByUdid($udid){
        if(empty($udid)) {
            return False;
        }
        $sql = " select * from {$this->_name} where udid='{$udid}' limit 1 ";
        $data = $this->fetchRow($sql);
        return $data;
    }

    function getUserInfoByUnionid($unionid){
        if(empty($unionid)) {
            return False;
        }
        $sql = " select uid from {$this->_name} where unionid='{$unionid}' limit 1 ";
        $data = $this->fetchRow($sql);
        return $data;
    }


    function getUidByDeviceserial($device_serial){
        if(empty($device_serial)) {
            return False;
        }
        $sql = "select uid from {$this->_name} where device_serial='{$device_serial}' limit 1 ";
        $data = $this->fetchRow($sql);
        return $data;
    }

    function getUserInfoByMobile($phone_num){
        if(empty($phone_num)) {
            return False;
        }

        $user_info = $this->find("mobile = {$phone_num}");
        return $user_info;
    }


    function getListData($page = 1,$page_size =  20,$condition = array()){
        $sql = " select * from {$this->_name} where 1 ";
        if(!empty($condition['uid'])) {
            $sql .= " and uid={$condition['uid']} ";
        }
        if(!empty($condition['parent_id'])) {
            $sql .= " and parent_id={$condition['parent_id']} ";
        }
        if(!empty($condition['mobile'])) {
            $sql .= " and mobile like '%{$condition['mobile']}%' ";
        }
        if(!empty($condition['ip'])) {
            $sql .= " and remote_ip like '%{$condition['ip']}%' ";
        }
        if(!empty($condition['address'])) {
            $sql .= " and address like '{$condition['address']}%' ";
        }
        if(!empty($condition['frozen'])) {
            $sql .= " and frozen={$condition['frozen']} ";
        }
        if(!empty($condition['ban'])) {
            $sql .= " and ban={$condition['ban']} ";
        }
        if($condition['start_date'] > 0) {
            $sql .= " and regtime>={$condition['start_date']} ";
        }
        if($condition['end_date'] > 0) {
            $sql .= " and regtime<{$condition['end_date']} ";
        }
        if(!empty($condition['is_ban'])) {
            $sql .= " and ban=1 ";
        }
        if(!empty($condition['is_frozen'])) {
            $sql .= " and frozen=1 ";
        }


        $sql .= " order by ";
        if(!empty($condition['sort'])){
            $sql .= " {$condition['sort']} desc, ";
        }
        $sql .= " uid desc ";
        $start = ($page -1 ) * $page_size;
        $sql .= " limit {$start}, {$page_size}";
        try{
            $data = $this->fetchAll($sql);
        }catch(Exception $ex){
            $data = array();
        }
        return $data;
    }

    function getListCount($condition = array()){
        $sql = " select count(*) as num from {$this->_name} where 1 ";
        if(!empty($condition['uid'])) {
            $sql .= " and uid={$condition['uid']} ";
        }
        if(!empty($condition['parent_id'])) {
            $sql .= " and parent_id={$condition['parent_id']} ";
        }
        if(!empty($condition['mobile'])) {
            $sql .= " and mobile like '%{$condition['mobile']}%' ";
        }
        if(!empty($condition['ip'])) {
            $sql .= " and remote_ip like '%{$condition['ip']}%' ";
        }
        if(!empty($condition['address'])) {
            $sql .= " and address like '{$condition['address']}%' ";
        }
        if(!empty($condition['frozen'])) {
            $sql .= " and frozen={$condition['frozen']} ";
        }
        if(!empty($condition['ban'])) {
            $sql .= " and ban={$condition['ban']} ";
        }
        if($condition['start_date'] > 0) {
            $sql .= " and regtime>={$condition['start_date']} ";
        }
        if($condition['end_date'] > 0) {
            $sql .= " and regtime<{$condition['end_date']} ";
        }
        if(!empty($condition['is_ban'])) {
            $sql .= " and ban=1 ";
        }
        if(!empty($condition['is_frozen'])) {
            $sql .= " and frozen=1 ";
        }

        $result = $this->fetchRow($sql);
        $num = 0;
        if(!empty($result['num'])) {
            $num = $result['num'];
        }
        return $num;
    }

    //创建token
    function mobile2code($mobile) {
        $source_string = 'fhNt4gn8FbDT3HY6AE9GQqr7ydBe5Ra';
        $num = $mobile;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 31;
            $code = $source_string[$mod].$code;
            $num = ($num - $mod) / 31;
        }

        if(empty($code[3])){
            $code = str_pad($code,4,'k',STR_PAD_LEFT);
        }

        return $code;
    }

    //token解密手机号
    function code2mobile($code) {
        $source_string = 'fhNt4gn8FbDT3HY6AE9GQqr7ydBe5Ra';
        if (strrpos($code, 'k') !== false){
            $code = substr($code, strrpos($code, 'k')+1);
        }
        $len = strlen($code);
        if($len<>7){//手机号转出来就是7位
            return 0;
        }
        $code = strrev($code);
        $num = 0;
        for ($i=0; $i < $len; $i++) {
            $num += strpos($source_string, $code[$i]) * pow(31, $i);
        }

        return $num;
    }



    #上传头像
    function updateAvatar($uid = 0,$upload_file = 'upload_file',$ext_name = '',$base64_string = ''){
        $pic = "";
        if(!empty($ext_name)){
            $remote_pic = uniqid(rand(), true).".".$ext_name;
            $cloud_obj = new CloudFileSystem();
            $flag = $cloud_obj->save($base64_string,$remote_pic);
            if($flag == $remote_pic){
                $pic = $remote_pic;
            }else{
                $this->throwException(-20054);
            }
        }else{
            $pic = $this->addPic($upload_file);
        }

        return $pic;
    }

}